import type { Config as PrismaConfig } from '@fill/client';
import { basename, join } from '@tauri-apps/api/path';
import { fs } from '@tauri-apps/api';
import { exists } from '@tauri-apps/api/fs';
import { FILL_TABLE_COLLECTION, NODE_TYPE, RECTIFICATION_TEXT, REPORT_TEXT, STATUS_TEXT, TABLE_COLLECTION } from '../../constants/default';
import type { IRectification } from '../../components/rectification/Content';
import type { IReport } from '../../components/report/Content';
import type { w_sp_def } from '../types/sp_def';
import { CONFIG_KEYS } from '../../constants/config';
import type { w_fwqpz_ } from '../types/fwqpz';
import type { w_yjpz_ } from '../types/yjpz';
import type { mbpz_ } from '../types/mbpz';
import type { fkyj_, fkyjxqb_ } from '../types/fkyj';
import type { IUploadFile } from '../../util';
import { appPath, filesPath, resourcePath } from '../../util';
import type { OtherFile } from '../types/other_file';
import type { IFillText } from '../../components/app/Fill';
import { Pipe } from './pipe';
import type { ILanhaiDataSchema, ILanhaiSpDef, ILanhaiSpNode, IPipe } from './interface';

export class Config extends Pipe implements IPipe {
  async import(data: ILanhaiDataSchema, sp_def: ILanhaiSpDef, sp_node: ILanhaiSpNode, configStore: IFillText['config']) {
    const report = await this.handleReport(data, sp_node, configStore);
    const rectification = await this.handleRectification(data, sp_node, configStore);
    const other = await this.handleOther(data);
    const text = [];
    report && text.push(REPORT_TEXT);
    rectification && text.push(RECTIFICATION_TEXT);

    const configs = [
      report,
      rectification,
      ...other,
    ].filter(item => !!item);

    return configs.length
      ? [
          {
            module: FILL_TABLE_COLLECTION.CONFIG,
            main: !!text.length,
            text,
            data: configs,
          },
        ]
      : [];
  }

  async handleOther(data: ILanhaiDataSchema) {
    try {
      const other = [
        [data.get(TABLE_COLLECTION.SERVER)?.data as w_fwqpz_[], CONFIG_KEYS.SERVER],
        [data.get(TABLE_COLLECTION.TIMEOUT)?.data as w_yjpz_[], CONFIG_KEYS.TIMEOUT],
        [data.get(TABLE_COLLECTION.EXAMPLE)?.data as mbpz_[], CONFIG_KEYS.EXAMPLE],
        [data.get(TABLE_COLLECTION.SP_DEF)?.data as w_sp_def[], CONFIG_KEYS.SP_DEF],
        [data.get(CONFIG_KEYS.DATA_SOURCE), CONFIG_KEYS.DATA_SOURCE],
        [data.get(CONFIG_KEYS.README), CONFIG_KEYS.README],
      ];
      console.log(other, data);
      // 转换文件
      const config = await Promise.all(
        other.map(async ([value, key]) => {
          if (key === CONFIG_KEYS.EXAMPLE) {
            value = await Promise.all(
              (value as mbpz_[]).map(async (item) => {
                const _value = JSON.parse(item.F_MBXX_);

                item.F_MBXX_ = JSON.stringify((
                  await Promise.all(_value.map(async (_item: OtherFile) => {
                    console.log('_item  =====', _item);
                    try {
                      const ext = (await basename(_item.fileName)).split('.')[1];
                      const file_name = `${_item.fileId}.${ext}`;
                      const path = await join(this.importPath, file_name);

                      if (!await exists(path)) {
                        console.log(`文件 - ${path} - 不存在`);
                        return null;
                      }

                      const target = await join(await filesPath(), file_name);
                      await fs.copyFile(path, target);

                      const url = target.replace(await appPath(), '');
                      return ({
                        uid: _item.fileId, // 文件id
                        name: _item.fileName, // 原名
                        fileName: file_name, // 文件名
                        base: url, // 相对路径
                        size: 0,
                        ext,
                        url: await resourcePath(url), // 资源全路径
                      } as IUploadFile);
                    }
                    catch (error) {
                      return null;
                    }
                  }))
                ).filter(item => !!item));
                return item;
              }),
            );
          }

          return {
            uuid: '',
            key,
            value: JSON.stringify(value),
            created_at: '',
            updated_at: '',
          } as PrismaConfig;
        }),
      );

      console.log(config);

      // 获取 F_XCZDX_NAME_
      const _name = data.get(TABLE_COLLECTION.OPINION)?.data as fkyj_[];
      config.push({
        uuid: '',
        key: CONFIG_KEYS.F_XCZDX_NAME_,
        value: _name[0].F_XCZDX_NAME_,
        created_at: '',
        updated_at: '',
      });

      // 获取 F_XCZDX_REF_ID_
      const _id = data.get(TABLE_COLLECTION.OPINION_RELATION)?.data as fkyjxqb_[];
      config.push({
        uuid: '',
        key: CONFIG_KEYS.F_XCZDX_REF_ID_,
        value: _id[0].F_XCZDX_REF_ID_,
        created_at: '',
        updated_at: '',
      });

      return config;
    }
    catch (error) {
      return [];
    }
  }

  async handleReport(data: ILanhaiDataSchema, sp_node: ILanhaiSpNode, configStore: IFillText['config']): Promise<PrismaConfig | undefined> {
    if (!sp_node[NODE_TYPE.REPORT] || !configStore[CONFIG_KEYS.REPORT])
      return;

    const report = configStore[CONFIG_KEYS.REPORT] as IReport;
    console.log(sp_node, report, !configStore[CONFIG_KEYS.REPORT]);
    // 当前节点
    const node = sp_node[NODE_TYPE.REPORT][report.uuid];

    const value: IReport = {
      ...report,
      examine: 0,
      status: STATUS_TEXT.NORMAL,
      node: node.F_DEF_ID_,
      next: node.F_NEXT_ || '',
      node_id: node.ID_,
      state: node.F_STATE_,
    };

    return {
      uuid: '',
      key: FILL_TABLE_COLLECTION.REPORT,
      value: JSON.stringify(value),
      created_at: '',
      updated_at: '',
    };
  }

  async handleRectification(data: ILanhaiDataSchema, sp_node: ILanhaiSpNode, configStore: IFillText['config']): Promise<PrismaConfig | undefined> {
    if (!sp_node[NODE_TYPE.RECTIFICATION] || !configStore[CONFIG_KEYS.RECTIFICATION])
      return;
    console.log(sp_node[NODE_TYPE.RECTIFICATION]);
    const rectification = configStore[CONFIG_KEYS.RECTIFICATION] as IRectification;
    // 当前节点
    const node = sp_node[NODE_TYPE.RECTIFICATION][rectification.uuid];

    const value: IRectification = {
      ...rectification,
      examine: 0,
      status: STATUS_TEXT.NORMAL,
      node: node.F_DEF_ID_,
      next: node.F_NEXT_ || '',
      node_id: node.ID_,
      state: node.F_STATE_,
    };

    return {
      uuid: '',
      key: FILL_TABLE_COLLECTION.RECTIFICATION,
      value: JSON.stringify(value),
      created_at: '',
      updated_at: '',
    };
  }

  async export() {
    return {};
  }
}
